import { injectable, inject } from 'tsyringe';
import { WebSocketEvents } from '../../domain/types';
import { IUserService } from '../../domain/interfaces/IUserService';
import { LoggerToken } from '../../domain/interfaces/ILogger';
import type { ILogger } from '../../domain/interfaces/ILogger';
import { WebSocketHandler } from '../../core/websocketHandler';

@injectable()
export class UserHandlers {
  constructor(
    @inject('IUserService') private userService: IUserService,
    @inject(LoggerToken) private logger: ILogger
  ) {}

  async handleLogin(ws: any, data: any, requestId?: string) {
    try {
      const { username, password } = data || {};
      const res = await this.userService.authenticate(username, password);
      if (!res) throw new Error('Invalid credentials');

      WebSocketHandler.sendMessage(ws, {
        event: WebSocketEvents.PONG,
        data: { token: (res as any).token, user: res },
        requestId,
        timestamp: Date.now()
      });
    } catch (err) {
      this.logger.error('Login failed', err as Error);
      WebSocketHandler.sendMessage(ws, { event: WebSocketEvents.ERROR, error: 'Auth failed', requestId, timestamp: Date.now() });
    }
  }

  async handleSetStatus(ws: any, data: any) {
    const { userId, status } = data || {};
    await this.userService.setStatus(userId, status);
  }
}
